package club.jdiy.admin.ueditor.upload;

import club.jdiy.admin.ueditor.PathFormat;
import club.jdiy.admin.ueditor.define.AppInfo;
import club.jdiy.admin.ueditor.define.BaseState;
import club.jdiy.admin.ueditor.define.FileType;
import club.jdiy.admin.ueditor.define.State;

import java.util.Map;

import club.jdiy.core.AppContext;
import club.jdiy.core.storage.Store;
import org.apache.commons.codec.binary.Base64;

public final class Base64Uploader {

	public static State save(AppContext context, String content, Map<String, Object> conf) {
		try {
			byte[] data = decode(content);

			long maxSize = (Long) conf.get("maxSize");

			if (!validSize(data, maxSize)) {
				return new BaseState(false, AppInfo.MAX_SIZE);
			}

			String suffix = FileType.getSuffix("JPG");

			String savePath = PathFormat.parse((String) conf.get("savePath"),
					(String) conf.get("filename"));

			savePath = savePath + suffix;
			String physicalPath = (String) conf.get("rootPath") + savePath;


			Store store = context.getStore("ueditor_img", "v1");
			String upurl = store.put(data, "scraw.jpg");

			State storageState = new BaseState(true);
			storageState.putInfo("size", 100);
			storageState.putInfo("title", "scraw.jpg");

			if (storageState.isSuccess()) {
				storageState.putInfo("url", upurl/*PathFormat.format(savePath)*/);
				storageState.putInfo("type", suffix);
				storageState.putInfo("original", "scraw.jpg");
			}


/*

		State storageState = StorageManager.saveBinaryFile(data, physicalPath);

		if (storageState.isSuccess()) {
			storageState.putInfo("url", PathFormat.format(savePath));
			storageState.putInfo("type", suffix);
			storageState.putInfo("original", "");
		}*/

			return storageState;
		}catch (Exception e){
			e.printStackTrace();
			return new BaseState(false, AppInfo.IO_ERROR);
		}
	}

	private static byte[] decode(String content) {
		return Base64.decodeBase64(content);
	}

	private static boolean validSize(byte[] data, long length) {
		return data.length <= length;
	}
	
}